///@file libmvdatatester.cpp Defines the entry point for the console application.

#include "stdafx.h"
#include "MVData.h"
#include <iostream>

using namespace std;


#ifndef _LINUX
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc, char * argv[])
#endif 
{
	
	cout << "reading file... ";
	// 打开一个已经存在的XML文件，并读入数据
	CMVData * pDataReader = new CMVData( TYPE_MVDATA_XML, "testfile.xml" );
	cout << " done!" << endl;

	if( NULL == pDataReader || !pDataReader->IsDataReady() )
	{
		cerr << "error in open xml file" << endl;
		return -1;
	}
		

	CMVData * pDataWriter = new CMVData();
	pDataWriter->CreateNew( TYPE_MVDATA_XML, "testfile2.xml" );

	if( NULL == pDataWriter || !pDataWriter->IsDataReady() )
	{
		cerr << "error in open xml file" << endl;
		return -1;
	}
		
	pDataWriter->SetFrameSize( pDataReader->GetFrameWidth(), pDataReader->GetFrameHeight() );

	int frame_count = pDataReader->GetFrameCount();
	if( frame_count <= 0 )
	{
		cerr << "frame_count <= 0" << endl;
		return -1;
	}

	const CMVDataMB * pMBReader = NULL;
	// TODO 必须从0帧开始，且连续
	for( int i=0; i<frame_count; i++ )
	{
		cout << "parsing frame " << i << "... ";

		pDataReader->ReadFrame( i );
		pDataWriter->WriteFrame( i );

		int mb_count = pDataReader->GetMBCount();
		if( mb_count <= 0 )
		{
			cerr << "mb_count <= 0 in frame " << i << endl;
			continue;
		}

		pMBReader = NULL;
		while ( pMBReader = pDataReader->GetNextMB( pMBReader ) )
		{
			CMVDataMB * pMBWriter = new CMVDataMB( pMBReader->GetMBType() );

			pMBWriter->SetCoordinate( pMBReader->GetCoordinateX(), pMBReader->GetCoordinateY() );

			const CMVDataBlock * pBlock = NULL;
			while( pBlock = pMBReader->GetNextBlock( pBlock ) )
			{
				pMBWriter->AddBlock( pBlock );
			}

			pDataWriter->AddMB( pMBWriter );
		}

		// TODO make it easier
		pDataWriter->SetFrameType( pDataReader->GetFrameType(), i );

		cout << " done!" << endl;

	}

	//pDataReader->Close(); //TODO Reader write all
	cout << "writing new file... ";
	pDataWriter->Close();
	cout << " done!" << endl;

	return 0;
}

